package logic

import (
	"context"
	"errors"
	"person/model/mysql"

	"person/userrpc/internal/svc"
	"person/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserByMobile(mysql.DB, in.Mobile); err != nil {
		user = mysql.User{
			Mobile:   in.Mobile,
			Password: in.Password,
		}
		if err := user.UserAdd(mysql.DB); err != nil {
			return nil, err
		}
	}

	if user.Password != in.Password {
		return nil, errors.New("密码错误请重新输入")
	}

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
